import { useHttpRequest } from '@/api/chunfeng/apiRequest'
import { UnwrapNestedRefs } from '@vue/reactivity'

import { reactive, ref } from 'vue'
import { QueryReceiptParam, ReceiptData } from '@/api/chunfeng/finance/receipt/interfaces'
import { useReceiptApi } from '@/api/chunfeng/finance/receipt'

import { Form } from 'ant-design-vue'
import moment from 'moment'

export const useReceiptListFunctions = () => {
  // name: 'ReceiptList',
  const { executeQueryRequest, executeCommandRequest } = useHttpRequest()
  const { queryReceipt } = useReceiptApi()

  const receiptDataSet = ref(Array<ReceiptData>())
  const csRef = ref()

  const paginationConfig = reactive({
    showSizeChanger: true,
  })

  interface ReceiptParam {
    customerId?: string
    occurredRange?: moment.Moment[]
  }

  const queryParams: UnwrapNestedRefs<ReceiptParam> = reactive({
    customerId: undefined,
    occurredRange: [],
  })

  const columns = [
    {
      title: '客户名称',
      dataIndex: 'customerName',
      key: 'customerName',
    },

    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      slots: { customRender: 'amount' },
    },
    {
      title: '发生日期',
      dataIndex: 'occurredAt',
      key: 'occurredAt',
    },
    {
      title: '未核销金额',
      dataIndex: 'unConfirmed',
      key: 'unConfirmed',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '操作',
      key: 'action',
      slots: { customRender: 'action' },
    },
  ]

  const { resetFields } = Form.useForm(queryParams, ref({}))

  function reset() {
    resetFields()
    csRef.value.reset()
  }

  function query() {
    receiptDataSet.value.length = 0
    const queryData: QueryReceiptParam = {
      customerId: queryParams.customerId,
      occurredStart: undefined,
      occurredEnd: undefined,
    }

    if (queryParams.occurredRange && queryParams.occurredRange.length > 1) {
      queryData.occurredStart = queryParams.occurredRange[0]
      queryData.occurredEnd = queryParams.occurredRange[1]
    }

    executeQueryRequest(queryReceipt(queryData), (results: ReceiptData[]) => {
      receiptDataSet.value.push(...results)
    })
  }

  function customerSelected(customerId: string) {
    queryParams.customerId = customerId
  }

  function showAr(receiptId: string) {}

  return {
    paginationConfig,
    queryParams,
    columns,
    reset,
    query,
    receiptDataSet,
    customerSelected,
    csRef,
    showAr,
  }
}
